﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace ProductCollector {
    public class WizeSearcher : ISiteSearcher {
        private const string SEARCH_URL = "http://www.wize.com/recommend/{0}?category_id={1}";
        private const string HOME_URL = "http://www.wize.com";
        public IList<Product> Search(SearchCriteria criteria) {
            var web = new HtmlWeb();
            string url = string.Format(SEARCH_URL, criteria.SearchValue, criteria.Category);
            List<Product> result = new List<Product>();

            HtmlDocument doc = web.Load(url);
            var gridNode = doc.DocumentNode.SelectSingleNode("//ul[contains(@class,'products')]");
            if (gridNode == null)
            {
                return result;
            }
            var allProds = gridNode.SelectNodes("./li[contains(@class,'product')]");

            foreach (HtmlNode node in allProds) {
                Product p = GetProductByNode(node);
                if (p != null) {
                    result.Add(p);
                }
                if (result.Count >= criteria.NumOfProduct) {
                    break;
                }
            }
            return result;
        }
        private Product GetProductByNode(HtmlNode liNode) {
            Product p = new Product();
            var thumImg = liNode.SelectSingleNode("./div/div[contains(@class,'product-list-item')]/img");
            if (thumImg != null) {
                p.ThumbImg = thumImg.GetAttributeValue("src", HOME_URL);

            }
            var title = liNode.SelectSingleNode("./div/div/div[contains(@class,'product-summary')]/h4/div/div/p");
            if (title != null) {
                p.ProductName = title.InnerText;
                
            }
            var orgLink = liNode.SelectSingleNode("./div/div/div[contains(@class,'product-summary')]/div[contains(@class,'hover-details')]/div/a[contains(@class,'product-expansion-card')]");
            if (orgLink != null)
            {
                var link = orgLink.GetAttributeValue("href", HOME_URL);
                link = link == HOME_URL ? HOME_URL : HOME_URL + link;
                p.OriginalUrl = link;
            }
            var price = liNode.SelectSingleNode("./div[contains(@class,'seller-content')]/div[contains(@class,'price')]");
            if(price != null)
            {
                p.FormattedPrice = price.InnerText;
            }
            return p;
        }
        public int CountProduct(SearchCriteria criteria) {
            throw new NotImplementedException();
        }
    }
}
